package com.myschool.server.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.myschool.server.manager.GradeManager;
import com.myschool.server.manager.SectionManager;
import com.myschool.server.manager.UserManager;
import com.myschool.server.model.Grade;
import com.myschool.server.model.Json;
import com.myschool.server.model.Rows;
import com.myschool.server.model.Section;
import com.myschool.server.model.User;
import com.myschool.server.model.UserType;

@Controller 
public class ClassConfigController {

	@Autowired
	private GradeManager gradeManager;
	
	@Autowired
	private SectionManager sectionManager;
	
	@Autowired
	UserManager userManager;
	
	@RequestMapping("ClassConfig.htm")
	public ModelAndView ClassConfig()
	{
	
		Set<Grade> gradeList = gradeManager.retrieveAllGrades(1L);
		 ModelAndView view = new ModelAndView("classConfig");
		 view.addObject("gradeList",gradeList);
		 return view;
	
	}
	
	@RequestMapping("classInformation.htm")
	public @ResponseBody
	Json classInformation(HttpServletRequest request,String sidx, String sord, int page, int rows, Boolean _search, String searchField, String searchOper, String searchString)
	{

		Json jsonData = new Json();
		try 
		{ 
		Long gradeID = Long.valueOf(request.getParameter("standardID"));
		Grade grade = new Grade();
		grade.setEntityId(gradeID);
		grade = gradeManager.retrieve(grade);
		
		
		int count = 1;
		String gradeName =grade.getGradeName(); 
		Set<Section> sections = grade.getSections();
		int size = sections.size();
		jsonData.rows = new Rows[size];
		for(Section section :sections )
		{
			User user = section.getClassTeacher();
			String teacherName = "";
			if(user!= null)
			teacherName = user.getFirstName();
			
			jsonData.rows[count -1] = new Rows();
			jsonData.rows[count -1].i = count;
			jsonData.rows[count -1].cell = new String[] {grade.getEntityId().toString(),section.getEntityId().toString(),
				section.getSectionName(),teacherName,""};
			count++;
		}
		jsonData.page = page; 
		jsonData.total = size;
		jsonData.record = size;
		
		//Below commented logic is used to parse all grades
	/*	Set<Grade> grades= 	gradeManager.retrieveAllGrades(1L);
	    int count =1;
 
		for(Grade grade : grades)
		{
			String id = Long.toString(grade.getEntityId());
			String gradeName =grade.getGradeName(); 
			Set<Section> sections = grade.getSections();
			int size = sections.size();
			jsonData.rows =expand(jsonData.rows, size + count -1);
			for(Section section :sections )
			{
				jsonData.rows[count -1].i = count;
				jsonData.rows[count -1].cell = new String[] {grade.getEntityId().toString(),section.getEntityId().toString(),"",
					section.getSectionName(),"",grade.getGradeName(),""};
				count++;
			}
			
		} 
		 
		jsonData.page = page; 
		jsonData.total = count;
		jsonData.record = count;
		*/
		 
		  
		}
		catch(Exception ex)
		{
			System.out.println(ex.getMessage());
			
		}

		return jsonData; 
	}
	
	private Rows[] expand(Rows[] array, int size) {
		Rows[] temp = new Rows[size];
		if(array != null && array.length > 0)
		{
	    System.arraycopy(array, 0, temp, 0, array.length);
	    for(int j = array.length; j < size; j++)
	        temp[j] = new Rows();
		}
		else
			for(int j = 0; j < size; j++)
		        temp[j] = new Rows();
	    return temp;
	}

	@RequestMapping(value=  "addClass.htm", method = RequestMethod.POST  )
	public  void addClass(HttpServletRequest request,HttpServletResponse response )
	{
		try
		{
			
			Grade grade = new Grade();

			Set<Section> sections = new HashSet<Section>();
			Set<Grade> grades = new HashSet<Grade>();
			Long school = (long) 1;
			String operation = request.getParameter("oper");

			String teacher =  request.getParameter("classTeacher");   
			String comments =  request.getParameter("comments"); 
			String sectionID =  request.getParameter("sectionID"); 
			if (operation.trim().equals("edit")) {
				
			User user =	 userManager.retrieve(Long.valueOf(teacher));
			Section section= sectionManager.retrieve(Long.valueOf(sectionID));
			section.setClassTeacher(user);
			
			sectionManager.create(section);
				
			}
			/*String standard =  request.getParameter("standard"); 
			String standardName =  request.getParameter("standardName"); 
			String sectionID =  request.getParameter("sectionID"); 
			String section =  request.getParameter("section");   
			String teacher =  request.getParameter("teacher");   
			String comments =  request.getParameter("comments");   
			grade.setGradeName(standardName);
			grade.setGradeNumber( Long.parseLong(standard));
			*/
			grade.setGradeName("1st Standard");
			grade.setGradeNumber(school);
			
			//grades.add(grade);

			//this.gradeManager.createSchoolGrades(school,grades );
			
			grade.setEntityId(3L);
			//grade = gradeManager.retrieve(grade);
			
			Section section = new Section();
			section.setGrade(grade);
			section.setSectionName("A");
			sections.add(section);
			//sectionManager.createSections(1L, sections);
			
			
		}
		catch(Exception ex)
		{
			System.out.println(ex.getMessage());
			
		} 
	
	}
	
	@RequestMapping("gradeList.htm")
	HttpServletResponse GetTeachersList(HttpServletRequest request,HttpServletResponse response)
	{ 

		try {
		String gradeList = "0:All";
		Set<Grade> grades= 	gradeManager.retrieveAllGrades(1L);
		
		for(Grade grade : grades)
		{
			String id = Long.toString(grade.getEntityId());
			String gradeName =grade.getGradeName();
				gradeList = gradeList + ";" + id + ":" + gradeName;
			System.out.println(gradeList);
			
		} 
		
			PrintWriter writer = response.getWriter();
			writer.append(gradeList);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response;
	
	}
	
	
	
	@RequestMapping("addGrades.htm")

	HttpServletResponse AddGrades(HttpServletRequest request,HttpServletResponse response)
	{ 

		try {
			
			int gradeRange = Integer.valueOf(request.getParameter("gradeRange"));
			int sectionCount = Integer.valueOf(request.getParameter("sectionGrade"));
			int startIndex = 0, endIndex = 0;
			switch(gradeRange)
			{
			
			case 1:
				startIndex = 1;
				endIndex = 10;
				break;
				
			case 2:
				break;
			case 3:
				break;
			default :
					startIndex = 0;
					endIndex = 0;
					break;
			
			}
			CreateGradesWithSection( startIndex, endIndex,sectionCount, 1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response;
	
	}
	
	//Creates the grades and adds a section to it.
	public void CreateGradesWithSection(int startIndex, int endIndex, int sectionCount, int school)
	{
		
		Set<Grade> grades = new HashSet<Grade>();
		
		for(int count =startIndex; count <= endIndex; count++)
		{
		Grade grade = new Grade();
		grade.setGradeName("Standard : " + (count));
		grade.setGradeNumber( (long) count);
		Set<Section> sections = new HashSet<Section>();
		for(int index = 0; index < sectionCount; index++)
		{ 
			Section section = new Section();
			char a = (char) (65 + index);
			section.setSectionName(String.valueOf(a));
			sections.add(section);
		}
	    grade.setSections(sections);
	    grades.add(grade);
		}
		
		Set<Grade> gradeList =  this.gradeManager.createSchoolGrades((long)school,grades);
		
		//Create an section for each Grade
	}
	
    @RequestMapping(value = "getSections.htm")
    public @ResponseBody String list(@RequestParam("standard") String standard) 
    { 
    	
        return "A:377;B:378;C:379";
    }

	
}
